from rest_framework.viewsets import GenericViewSet, ModelViewSet
from utils.view import CommonListModelMixin, CommonUpdateModelMixin
from .models import Address
from .serializer import AddressSerializer, UserOneSerializer, UserShipSerializer
from utils.response import APIResponse
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import APIException


class AddressView(ModelViewSet, CommonListModelMixin):
    queryset = Address.objects.all()
    serializer_class = AddressSerializer
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user_id']

    def create(self, request, *args, **kwargs):
        res = super().create(request, *args, **kwargs)
        return APIResponse(result=res.data)

    def update(self, request, *args, **kwargs):
        res = super().update(request, *args, **kwargs)
        return APIResponse(result=res.data)

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return UserOneSerializer
        return AddressSerializer


class ShipAddressView(GenericViewSet, CommonListModelMixin):
    queryset = Address.objects.all()
    serializer_class = UserOneSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user_id']

    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        result = res.data.get('result')
        if result:
            for item in result:
                if item.get('ship_address'):
                    item_list = item
            return APIResponse(result=item_list)
        else:
            raise APIException('没有地址')


class UpdateShipView(GenericViewSet, CommonUpdateModelMixin):
    queryset = Address.objects.all()
    serializer_class = UserShipSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user_id']


class DefaultAddressView(GenericViewSet, CommonListModelMixin):
    queryset = Address.objects.all()
    serializer_class = UserOneSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['user_id']

    def list(self, request, *args, **kwargs):
        res = super().list(request, *args, **kwargs)
        result = res.data.get('result')
        if result:
            for item in result:
                if item.get('isDefault'):
                    item_list = item
            return APIResponse(result=item_list)
        else:
            raise APIException('没有地址')
